import os, tempfile

def get_upload(request):
  # AJAX Upload will pass the filename in the querystring if it is the "advanced" ajax upload
  if request.is_ajax( ):
    # the file is stored raw in the request
    upload = request
    is_raw = True
    try:
      filename = request.GET[ 'qqfile' ]
    except KeyError:
      print 'ajax_upload', "AJAX request not valid"
      return HttpResponseBadRequest( "AJAX request not valid" )
  # not an ajax upload, so it was the "basic" iframe version with submission via form
  else:
    is_raw = False
    if len( request.FILES ) == 1:
      # FILES is a dictionary in Django but Ajax Upload gives the uploaded file an
      # ID based on a random number, so it cannot be guessed here in the code.
      # Rather than editing Ajax Upload to pass the ID in the querystring, note that
      # each upload is a separate request so FILES should only have one entry.
      # Thus, we can just grab the first (and only) value in the dict.
      upload = request.FILES.values( )[ 0 ]
    else:
      print 'ajax_upload', "Bad Upload"
      raise Http404( "Bad Upload" )
    filename = upload.name
 
  return upload, filename, is_raw

def save_upload( uploaded, filename, raw_data ):
  ''' raw_data: if True, upfile is a HttpRequest object with raw post data
      as the file, rather than a Django UploadedFile from request.FILES '''
  try:
    with open(os.path.join(tempfile.mkdtemp(), filename), 'wb+') as dest:
      # if the "advanced" upload, read directly from the HTTP request
      # with the Django 1.3 functionality
      if raw_data:
        foo = uploaded.read( 1024 )
        while foo:
          dest.write( foo )
          foo = uploaded.read( 1024 )
      # if not raw, it was a form upload so read in the normal Django chunks fashion
      else:
        for c in uploaded.chunks( ):
          dest.write( c )
      dest.flush()
      return True, dest.name
  except IOError:
    print 'save_upload IOError'
    # could not open the file most likely
    return False, None

